// https://leetcode.cn/problems/unique-binary-search-trees-ii/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> getAns(int n, int start) {
        vector<TreeNode*> ans;
        if (n == 0) {
            ans.push_back(NULL);
            return ans;
        }
        for (int i = 1; i <= n; ++i) {
            vector<TreeNode*> left = getAns(i - 1, start);
            vector<TreeNode*> right = getAns(n - i, start + i);
            for (auto& l: left) {
                for (auto& r: right) {
                    // TreeNode* root = new TreeNode(i); // 是全局而不是局部的第i个节点，需要引入start
                    TreeNode* root = new TreeNode(start + i);
                    root->left = l;
                    root->right = r;
                    ans.push_back(root);
                }
            } 
        }
        return ans;
    }
    vector<TreeNode*> generateTrees(int n) {
        return getAns(n, 0);        
    }
};